package top.tervest.easyshare.common.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.UUID;

/**
 * @author ZhangNanNan
 * @create 2019-07-17 17:40
 */
@Component
public class AuthUtil {
    @Resource(name = "SJRedisTemplate")
    private RedisTemplate redisTemplate;
    @Autowired
    private  AuthenticationManager authenticationManager;

    private static AuthUtil util;
    @PostConstruct
    public void init(){
        util = this;
}
    public static String generateToken(){
        return UUID.randomUUID().toString();
    }

    /**
     * 认证用户
     * @param token
     */
    public static String auth(UsernamePasswordAuthenticationToken token){
        Authentication authenticate = util.authenticationManager.authenticate(token);
        String tokenName = generateToken();
        util.redisTemplate.opsForHash().put("users",tokenName,authenticate);
        return tokenName;
    }

    /**
     * 获取用户认证信息
     */
    public static Authentication getAuthentication(String tokenName){
        return (Authentication)util.redisTemplate.opsForHash().get("users", tokenName);
    }
}
